﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using PVICommon;
using System.Data.SqlClient;

namespace PVI_Sunlife
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        DBTranfer t = new DBTranfer();
        StringBuilder sbMenu = new StringBuilder();
        DataTable dtPage = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltMenu.Text = DisplayMenu();
            }
        }

        public string DisplayMenu()
        {
            //Get Data from Database
            SqlConnection objCon = t.GetConnect();
            string strSql =
                "SELECT PageId,ParentID,PageAlias,PageName,LinkTo,Target,DisplayOrder,Status  FROM tblNavigation ";
            SqlCommand objCommand = new SqlCommand(strSql, objCon);
            objCon.Open();
            SqlDataReader dataReader = objCommand.ExecuteReader();

            dtPage.Load(dataReader);
            objCon.Close();

            //Display root menu (with parentid=0)
            sbMenu.Append("<ul>");
            for (int i = 0; i < dtPage.Rows.Count; i++)
            {
                if (dtPage.Rows[i]["ParentID"].ToString() == "0")
                {
                    sbMenu.AppendFormat("<li style=\"border-bottom: 7px solid #ed9000;\"><a href=\"{0}\" class=\"menu-link\">{1}</a>", dtPage.Rows[i]["LinkTo"], dtPage.Rows[i]["PageName"]);
                    BuildMenu((Int32)dtPage.Rows[i]["PageId"]);
                }
            }

            sbMenu.Append("</ul>");

            return sbMenu.ToString();
        }

        public void BuildMenu(Int32 parentId)
        {
            List<DataRow> lstChilds = new List<DataRow>();
            for (Int32 i = 0; i < dtPage.Rows.Count; i++)
            {
                if ((Int32)dtPage.Rows[i]["ParentID"] == parentId)
                {
                    lstChilds.Add(dtPage.Rows[i]);
                }
            }

            if (lstChilds.Count() > 0)
            {
                sbMenu.Append("<ul>");
                foreach (var row in lstChilds)
                {
                    sbMenu.AppendFormat("<li><a href=\"{0}\" style=\"background:#faa21b\">{1}</a>", row["LinkTo"], row["PageName"]);
                    BuildMenu((Int32)row["PageId"]);
                }
                sbMenu.Append("</ul>");
            }
            else
            {
                sbMenu.Append("</li>");
            }
        }
    }
}
